package com.hub.netty.server.config;


import com.hub.netty.base.handler.MessageDecodeHandler;
import com.hub.netty.base.handler.MessageEncodeHandler;
import com.hub.netty.server.handler.ServerListenerHandler;
import com.hub.netty.server.handler.TokenHandshakeHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * @ author 令狐冲
 * @ date & time 2025/2/6 14:43
 */
public class NettyServerHandler extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        // 数据分割符
        String delimiterStr = "##@##";
        ByteBuf delimiter = Unpooled.copiedBuffer(delimiterStr.getBytes());
        ChannelPipeline pipeline = socketChannel.pipeline();
        // 添加 HTTP 编解码器
        pipeline.addLast(new HttpServerCodec());
        // 聚合 HTTP 请求
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(new TokenHandshakeHandler());
        // 使用自定义处理拆包/沾包，并且每次查找的最大长度为1024字节
        pipeline.addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
        // 将上一步解码后的数据转码为Message实例
        pipeline.addLast(new MessageDecodeHandler());
        // 对发送客户端的数据进行编码，并添加数据分隔符
        pipeline.addLast(new MessageEncodeHandler(delimiterStr));
        // 对数据进行最终处理
        pipeline.addLast(new ServerListenerHandler());
        pipeline.addLast(new WebSocketServerProtocolHandler("/call", null, true, 65535));
    }
}
